<template>
  <div class="app-container">
    <el-row>
      <el-col :span="12">
        <el-form ref="form" :model="form" label-width="140px">
          <el-form-item label="名称">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="进货价格">
            <el-input v-model="form.purchase_price" />
          </el-form-item>
          <el-form-item label="出售价格">
            <el-input v-model="form.sale_price" />
          </el-form-item>
          <el-form-item label="品牌">
            <el-select
              v-model="form.brand_id"
              class="full-width"
              filterable
              placeholder="请选择品牌"
            >
              <el-option
                v-for="brand in brands"
                :key="brand.id"
                :label="brand.name"
                :value="brand.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :loading="submitLoading" @click="onSubmit">保存</el-button>
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { create, findById, update } from '@/api/product'
import { all as getAllBrand } from '@/api/brand'

export default {
  name: 'ProductCreate',
  data() {
    return {
      form: {},
      submitLoading: false,
      isEdit: false,
      id: 0,
      brands: []
    }
  },
  created() {
    const id = this.$route.params && this.$route.params.id
    if (id) {
      this.isEdit = true
      this.id = id
      this.fetchData(id)
    }

    this.getAllBrand()
  },
  methods: {
    onSubmit() {
      this.submitLoading = true

      if (this.isEdit) {
        update(this.id, this.form).then((response) => {
          this.submitLoading = false
          this.$message.success(response.message)
        }).catch(() => {
          this.submitLoading = false
        })
      } else {
        create(this.form).then((response) => {
          this.submitLoading = false
          this.$message.success(response.message)
        }).catch(() => {
          this.submitLoading = false
        })
      }
    },
    fetchData(id) {
      findById(id).then((response) => {
        this.form = response.data
      })
    },
    getAllBrand() {
      getAllBrand().then((response) => {
        this.brands = response.data
      })
    }
  }
}
</script>

<style scoped>

</style>
